﻿
#include <stdexcept>
#include <iostream>
#include <fstream>
#include "WinFunc.h"
#include "Misc.h"
#include "Log.h"

namespace Base {

	inline void ConsolePrintWithFileAndLineNO(const char* file, int line, const char* msg) {
		//printf("[%s:%d] %s\n", file, line, msg);
		std::cout << "[" << file << ":" << line << "] " << msg << std::endl;
	}

	inline void ConsolePrint(const char* msg) {
		std::cout << msg << std::endl;
	}

	static void WriteToFile(const char* file, int line, const fs::path& filePath, const char* msg) {
		std::ofstream ff(filePath, std::ios_base::app);
		if (ff.is_open()) {
			ff << "[" << file << ":" << line << "] " << msg << std::endl;
			ff.close();
		}
		else {
			Debug::ThrowOrMessageBox("WriteToFile error!");
		}
	}

	Log* Log::s_Log = nullptr;

	Log::Log() {
		if (s_Log != nullptr)
		{
			Debug::ThrowOrMessageBox("s_Log already exist!");
		}
		s_Log = this;

		auto workingDir = WinFunc::GetWorkingDir();
		ConsolePrint(workingDir.c_str());

		fs::path logDir = workingDir + "/../logs";

		// init logpath
		if (!fs::exists(logDir))
		{
			fs::create_directory(logDir);
		}
		m_filePath = logDir / "log.txt";
	}

	Log::~Log() {

	}

	void Log::Info(const char* file, int line, const std::string& msg) {
		ConsolePrintWithFileAndLineNO(file, line, msg.c_str());
		if (s_Log->m_LogToFile)
		{
			WriteToFile(file, line, s_Log->m_filePath, msg.c_str());
		}
	}

}